#pragma once
#include "Log.hpp"
#include "InetAddr.hpp"
#include <string>
#include<cstdio>
class Command
{
public:
    Command() {}
    string Excute(const string& cmdstr)
    {
        string result;
        FILE *fp = popen(cmdstr.c_str(), "r");
        if(fp)
        {
            char line[512];
            while(fgets(line,sizeof(line),fp))
            {
                result += line;
            }
            return result.empty()?"success":result;
        }
        else{
            return "execute error";
        }
    }
    void HanderCommand(int sockfd, InetAddr addr)
    {
        while (1)
        {
            char buf[512];
            ssize_t n = ::recv(sockfd, buf, sizeof(buf) - 1,0);
            if (n > 0)
            {
                buf[n] = 0;
                string msg = "[" + addr.Ip() + "]:" + buf;
                LOG(INFO, "%s\n", msg.c_str());
                string result=Excute(buf);
                ::send(sockfd, result.c_str(), result.size(), 0);
            }
            else if (n == 0)
            {
                LOG(INFO, "client %s quit\n", addr.Ip().c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read %s error\n", addr.Ip().c_str());
                break;
            }
        }
        ::close(sockfd);
    }
    ~Command() {}
};